<template>
    <div class="main user-admin-list">
        <div class="filter-container">
            <!-- 手机号：<el-input @keyup.enter.native="search" class="filter-item" placeholder="按手机号搜索" v-model="params.search" clearable></el-input>
            姓名：<el-input @keyup.enter.native="search" class="filter-item" v-model="params.realNameSearch" clearable></el-input>
            用户状态：<el-select class="filter-item" v-model="params.userStatus" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button> -->
            <el-button v-if="rightsButtons['add']" type="success" icon="el-icon-plus" class="filter-item" @click="showAdd">新建</el-button>
        </div>
        <search-form
          :listQuery="listQuery"
          :queryConfig="queryConfig"
          :labelWidth="100"
          :search="search"
        />
        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="姓名" prop="realname"></el-table-column>
            <el-table-column align="center" label="手机号" prop="username"></el-table-column>
            <el-table-column align="center" label="所属角色">
                <template slot-scope="scope">
                    <div class="text-justify">
                        <p v-text="scope.row.roleNames"></p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="状态" width="200">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.deleteFlag"
                        @change="updateStatus(scope.row)"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-text="启用"
                        inactive-text="禁用"
                        :active-value="1"
                        :inactive-value="0"
                        :disabled="!rightsButtons['operate']">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="200" v-if="rightsButtons['edit'] || rightsButtons['passwordReset']">
                <template slot-scope="scope">
                    <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                    <el-button v-if="rightsButtons['passwordReset']" type="danger" size="mini" @click="resetPassword(scope.row)">重置密码</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="total > 0">
            <el-pagination @current-change="handleCurrentChange" @size-change="handleSizeChange" :current-page.sync="listQuery.page" :page-size="listQuery.pageSize" :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
        <el-dialog :title="editItem.id ? '编辑用户' : '新建用户'" :visible.sync="showEditPop">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="姓名:" prop="realname">
                    <el-input v-model="editItem.realname"></el-input>
                </el-form-item>
                <el-form-item label="手机号:" prop="username">
                    <el-input type="tel" v-model="editItem.username"></el-input>
                </el-form-item>
                <template v-if="!editItem.id">
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="editItem.password"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码:" prop="chkpassowrd">
                        <el-input type="password" v-model="editItem.chkpassowrd"></el-input>
                    </el-form-item>
                </template>
                <el-form-item label="角色:" prop="roleIds">
                    <el-checkbox-group v-model="editItem.roleIds">
                        <el-checkbox v-for="item of roles" :key="item.id" :label="item.id">{{item.description}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="组织机构:" prop="organizationId">
                    <el-select v-model="editItem.organizationId" :disabled="!!editItem.id">
                        <el-option v-for="item in organizationList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                    <!--<el-checkbox-group v-model="editItem.organizationId">
                        <el-checkbox v-for="item of roles" :key="item.id" :label="item.id">{{item.role}}</el-checkbox>
                    </el-checkbox-group>-->
                </el-form-item>
                <el-form-item label="是否启用:">
                    <el-switch
                        v-model="editItem.deleteFlag"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :disabled="btnDisabled">保存</el-button>
                <el-button @click="showEditPop = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import SearchForm from '@/components/searchForm'
    import {regexp} from '../../../utils/tools'
    import {getRoleList} from '../../../api/common'

    export default {
        name: 'userAdminList',
        data() {
            const validTel = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('不能为空'));
                }
                if (this.editItem.id && this.editName === value) {
                    return callback();
                }
                if (!regexp.tel.test(value)) {
                    return callback(new Error('手机号格式错误'));
                }
                this.btnDisabled = true;
                this.request({
                    url: '/bsnl-authority/user/valid',
                    method: 'get',
                    params: {
                        username: value
                    }
                }).then(({data}) => {
                    if (data != 1) {
                        return callback(new Error('手机号已被注册'));
                    }
                    this.btnDisabled = false;
                    return callback();
                }).catch(err => {
                    this.btnDisabled = false;
                    return callback(new Error(err));
                });
            };
            const pwRule = {
                pattern: regexp.password,
                message: '密码6-20个大小写字母或数字',
                trigger: 'change'
            };
            return {
                list: [],
                listQuery: {
                  search: '',
                  realNameSearch: '',
                  userStatus: '',
                  page: 1,
                  pageSize: 20,
                },
                queryConfig: [
                  {
                    prop: 'search',
                    type: 'input',
                    label: '手机号',
                    maxlength: '100'
                  },
                  {
                    prop: 'realNameSearch',
                    type: 'input',
                    label: '姓名'
                  },
                  {
                    prop: 'userStatus',
                    type: 'select',
                    label: '用户状态',
                    data: [
                      {
                        value: '',
                        label: '全部'
                      },
                      {
                        value: 1,
                        label: '启用'
                      },
                      {
                        value: 0,
                        label: '禁用'
                      }
                    ]
                  }
                ],
                query: {},
                total: 0,
                editItem: {
                    roleIds: []
                },
                editName: '',
                editRule: {
                    realname: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        {max: 100, message: '不能超过100字符', trigger: 'change'},
                        {pattern: /[\a-zA-Z0-9\u4e00-\u9FA5]+$/, message: '不能含有特殊字符', trigger: 'change'},
                    ],
                    username: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        {pattern: regexp.tel, message: '手机号格式错误', trigger: 'change'},
                        {validator: validTel, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        pwRule
                    ],
                    chkpassowrd: [
                        {required: true, message: '不能为空', trigger: 'change'},
                        pwRule,
                        {
                            validator: (rule, value, callback) => {
                                if (!value) {
                                    return callback();
                                }
                                if (value !== this.editItem.password) {
                                    return callback(new Error('两次输入的密码不相同'));
                                }
                                callback();
                            },
                            trigger: 'change'
                        }
                    ],
                    newPassword: [
                        {required: false, message: '不能为空', trigger: 'blur'},
                        pwRule
                    ],
                    repeatPassowrd: [
                        {required: false, message: '不能为空', trigger: 'blur'},
                        pwRule,
                        {
                            validator: (rule, value, callback) => {
                                if (!value) {
                                    return callback();
                                }
                                if (value !== this.editItem.newPassword) {
                                    callback(new Error('两次输入的密码不相同'));
                                }
                                return callback();
                            },
                            trigger: 'change'
                        }
                    ],
                    roleIds: [
                        {required: true, message: '请选择', trigger: 'change'},
                    ]
                },
                roles: [],
                organizationList: [],
                showEditPop: false,
                listLoading: false,
                btnDisabled: false,
            }
        },
        components: {
          SearchForm
        },
        created() {
            this.getList();
            this.getRoleList();
            this.getOrganizationList();
        },
        methods: {
            // 获取列表
            getList() {
                this.listLoading = true;
                this.request({
                    url: '/bsnl-authority/user/list',
                    method: 'get',
                    params: {
                        ...this.listQuery,
                        offset: this.listQuery.page - 1,
                        limit: this.listQuery.pageSize
                    }
                }).then(({rows, total}) => {
                    this.list = rows;
                    this.total = total;
                    this.listLoading = false;
                }).catch(err => {
                    this.list = [];
                    this.total = 0;
                    this.listLoading = false;
                });
            },
            // 获取角色列表
            getRoleList(){
                getRoleList({
                    offset: 0,
                    limit: 99999
                }).then(({rows}) => {
                    this.roles = rows;
                }).catch(err => {
                    this.roles = [];
                });
            },
            // 获取组织机构列表
            getOrganizationList(){
                this.request({
                    url: '/bsnl-authority/organization/tree',
                    method: 'get',
                    params: {}
                }).then(({data}) => {
                    this.organizationList = data;
                }).catch(err => {
                    this.organizationList = [];
                });
            },
            // 显示新建
            showAdd() {
                this.editItem = {
                    realname: '',
                    username: '',
                    password: '',
                    chkpassowrd: '',
                    organizationName: '',
                    organizationId: 1,
                    roleIds: [],
                    deleteFlag: 0
                };
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            // 显示编辑
            showEdit(item) {
                const {id, realname, username, organizationId, roleIdList, deleteFlag} = item;
                this.editName = username;
                this.editItem = {
                    id,
                    realname,
                    username,
                    organizationName: '',
                    organizationId: organizationId,
                    roleIds: roleIdList,
                    deleteFlag
                };
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            // 保存
            save() {
                this.$refs.editItem.validate(valid => {
                    if (!valid) {
                        return false;
                    }
                    let url = '/bsnl-authority/user/create';
                    if(this.editItem.id){
                        url = '/bsnl-authority/user/update';
                    }
                    this.btnDisabled = true;
                    this.request({
                        url,
                        method: 'post',
                        data: {
                            ...this.editItem,
                            roleIds: this.editItem.roleIds.toString()
                        }
                    }).then(() => {
                        this.btnDisabled = false;
                        this.editItem = {};
                        this.showEditPop = false;
                        this.$message.success('保存成功');
                        this.getList();
                    }).catch(err => {
                        console.log(err);
                        this.btnDisabled = false;
                    });
                });
            },
            // 启用/禁用
            updateStatus({id, deleteFlag}) {
                this.request({
                    url: '/bsnl-authority/user/update',
                    method: 'post',
                    data: {
                        id,
                        deleteFlag
                    }
                }).then(() => {
                    this.$message.success(deleteFlag == 1 ? '启用成功' : '禁用成功');
                }).catch(err => {
                    this.$message.error(err);
                });
            },
            // 重置密码
            resetPassword(item) {
                this.$confirm(`确定要重置 ${item.realname} 的密码吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.request({
                        url: `/bsnl-authority/user/${item.id}/reset/password`,
                        method: 'post',
                        data:{}
                    }).then(() => {
                        this.$message.success('重置密码成功');
                    }).catch(err => {
                        console.log(err);
                    });
                }).catch(err => {
                    console.log(err);
                });
            },
            // 搜索
            search() {
                this.listQuery.page = 1;
                this.query = {
                  ...this.listQuery
                };
                this.getList();
            },
            // 切换分页
            handleCurrentChange(page) {
              this.listQuery.page = page;
              this.getList();
            },
            // 切换每页条数
            handleSizeChange (pageSize) {
              this.listQuery.pageSize = pageSize;
              this.getList();
            }
        }
    }
</script>
